package com.yupi.springbootinit.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

public class FanoutConsumer {
    private static final String EXCHANGE_NAME = "fanout_exchange";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        Channel channel2 = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
        channel2.exchangeDeclare(EXCHANGE_NAME, "fanout");

        String quequeName1 = "小王队列";
        String quequeName2 = "小李队列";

        channel.queueDeclare(quequeName1, true, false, false, null);
        channel2.queueDeclare(quequeName2, true, false, false, null);

        channel.queueBind(quequeName1, EXCHANGE_NAME, "");
        channel2.queueBind(quequeName2, EXCHANGE_NAME, "");


        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [小王队列] Received '" + message + "'");
        };
        DeliverCallback deliverCallback2 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [小李队列] Received '" + message + "'");
        };
        channel.basicConsume(quequeName1, true, deliverCallback, consumerTag -> {
        });
        channel2.basicConsume(quequeName2, true, deliverCallback2, consumerTag -> {
        });
    }
}